<template>
  <Select ref="select" placeholder="输入司机姓名搜索" v-model="model" @on-change="change" filterable remote :multiple="multiple" :remote-method="search" :loading="isLoading" :clearable="clearable" transfer>
    <Option v-for="(v, i) in datas" :value="v.value" :key="`driver-complete-option-${v.value}`">{{`${v.label}${showTel?`(${v.tel})`:''}`}}</Option>
  </Select>
</template>

<script>
  import {post}  from '@/util/request'

  export default {
    props: {
      value:{type: [String, Number, Array],default: ''},
      multiple:{type: Boolean,default: false},
      showTel:{type: Boolean,default: false},
      clearable:{type:Boolean,default: false},
      orgid:{type:String}
    },
    mounted(){
      this.$emit('on-init',this);
    },
    data() {
      return {
        model:this.value,
        datas: [],
        isLoading: false,
        selectItem:null
      }
    },
    watch: {
      value(v){
        this.model = v;
      },
      model(v){
        this.$emit('input',v);
      }
    },
    computed:{

    },
    methods:{
      search(query){
        if(query) {
          let search = {orgIds:this.orgid,key:query};
          this.isLoading = true;
          post('/common/findDriverByOrgId', search).then(res => {
            this.isLoading = false;
            let json = res.data;
            if (json.sta === 200) {
              this.datas = json.data.map(o => {
                return {value:o.id,label:o.name,tel:o.tel};
              });
            }
          });
        } else {
          this.datas = [];
        }
      },
      change(v){
        let item = this.datas.find(o => o.value === v);
        this.$emit('on-change',item);
      },
      getItem(v){
        let item = this.datas.find(o => o.value === v);
        return item;
      },
      setSelected(){
        // this.$refs.select.model = this.selectItem.value;
        // this.$refs.select.setQuery(this.selectItem.label);
        // this.$refs.select.lastQuery = this.selectItem.label;
        this.datas = [this.selectItem];
        if (this.selectItem){
          setTimeout(() => {
            setTimeout(() => {
              if (this.multiple){
                this.model = [this.selectItem.value];
                this.$nextTick(() => {
                  this.$refs.select.updateMultipleSelected();
                });
              }else{
                this.model = this.selectItem.value;
                this.$refs.select.setQuery(this.selectItem.label);
                this.$refs.select.lastQuery = this.selectItem.label;
              }
            },0);
          },0)
        }
      },
      setOptions(v){
        this.selectItem = v;
        this.setSelected();
      }
    }
  }
</script>
